import { writeFile } from 'fs/promises'
import { NextRequest, NextResponse } from 'next/server'
import path from 'path'
import fs from 'fs'

export async function POST(request: NextRequest) {
    console.log("开始处理文件上传请求")
    try {
        console.log("正在读取文件数据...")
        const file = request.body
        const contentType = request.headers.get("content-type") || "application/octet-stream"
        const fileName = request.headers.get("x-vercel-filename") || "image.png"
        const product_id = request.headers.get("x-product-id")
        console.log(`product_id:`+product_id)

        if (!file) {
            console.log("错误：未检测到文件")
            return NextResponse.json({ success: false, message: "请选择文件" })
        }

        console.log(`接收到文件: ${fileName}, 类型: ${contentType}`)

        // 读取文件内容
        const arrayBuffer = await new Response(file).arrayBuffer()
        const buffer = Buffer.from(arrayBuffer)
        console.log(`buffer大小: ${buffer.length} bytes`)

        // 确保上传目录存在，没有则创建
        const uploadDir = path.join(process.cwd(), 'uploads',product_id+'')

        if (!fs.existsSync(uploadDir)) {
            fs.mkdirSync(uploadDir, { recursive: true })
            console.log(`创建上传目录: ${uploadDir}`)
        } else {
            console.log(`上传目录已存在: ${uploadDir}`)
        }
        
        // 生成唯一文件名
        const uniqueFilename = `${Date.now()}-${fileName}`
        const filePath = path.join(uploadDir, uniqueFilename)
        console.log(`完整文件路径: ${filePath}`)
        
        // 写入文件
        console.log("开始写入文件...")
        await writeFile(filePath, buffer)
        console.log("文件写入成功")

        // 读取配置文件
        const configPath = path.join(process.cwd(), 'config.json')
        let config = { serviceUrl: 'http://localhost:3000' } // 默认值
        
        try {
          const fileContent = fs.readFileSync(configPath, 'utf-8')
          config = JSON.parse(fileContent)
        } catch (error) {
          if (error.code !== 'ENOENT') {
            throw error
          }
          console.warn('使用默认配置，因为config.json文件不存在')
        }
        
        const fileUrl = `${config.serviceUrl}/api/uploads/${product_id}/${uniqueFilename}`

        console.log(`文件访问URL: ${fileUrl}`)
        
        return NextResponse.json({
            success: true,
            url: fileUrl,
            fileInfo: {
                name: fileName,
                type: contentType,
                path: filePath
            }
        });
        
    } catch (error) {
        console.error("文件上传失败:", error)
        return NextResponse.json({ 
            success: false, 
            message: "上传失败",
            error: error instanceof Error ? error.message : "未知错误"
        })
    }
}